import cv2 as cv
import  mediapipe as mp
from tqdm import tqdm
import time
import  matplotlib.pyplot as plt


# 导入三维人脸关键点检测模型
mp_face_mesh=mp.solutions.face_mesh
# help(mp_face_mesh.FaceMesh)

model=mp_face_mesh.FaceMesh(
    static_image_mode=False,#TRUE:静态图片/False:摄像头实时读取
    refine_landmarks=True,#使用Attention Mesh模型
    max_num_faces=5,#最多检测几张人脸
    min_detection_confidence=0.5, #置信度阈值，越接近1越准
    min_tracking_confidence=0.5,#追踪阈值
)


# 导入可视化函数和可视化样式
mp_drawing=mp.solutions.drawing_utils
mp_drawing_styles=mp.solutions.drawing_styles

# 处理单帧的函数

def process_frame(img):
    #记录该帧处理的开始时间
    start_time=time.time()
    img_RGB=cv.cvtColor(img,cv.COLOR_BGR2RGB)
    results=model.process(img_RGB)
    if results.multi_face_landmarks:
        for face_landmarks in results.multi_face_landmarks:
            # mp_drawing.draw_detection(
            #  image=img,
            # landmarks_list=face_landmarks,
            # connections=mp_face_mesh.FACEMESH_TESSELATION,
            # landmarks_drawing_spec=None,
            # landmarks_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style()
            # )

            # 绘制人脸网格
            mp_drawing.draw_landmarks(
                image=img,
                landmark_list=face_landmarks,
                connections=mp_face_mesh.FACEMESH_TESSELATION,
                # landmark_drawing_spec为关键点可视化样式，None为默认样式（不显示关键点）
                # landmark_drawing_spec=mp_drawing_styles.DrawingSpec(thickness=1,circle_radius=2,color=[66,77,229]),
                landmark_drawing_spec=None,
                connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style()
            )
            # 绘制人脸轮廓、眼睫毛、眼眶、嘴唇
            mp_drawing.draw_landmarks(
                image=img,
                landmark_list=face_landmarks,
                connections=mp_face_mesh.FACEMESH_CONTOURS,
                # landmark_drawing_spec为关键点可视化样式，None为默认样式（不显示关键点）
                # landmark_drawing_spec=mp_drawing_styles.DrawingSpec(thickness=1,circle_radius=2,color=[66,77,229]),
                landmark_drawing_spec=None,
                connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style()

            )
            # 绘制瞳孔区域
            mp_drawing.draw_landmarks(
                image=img,
                landmark_list=face_landmarks,
                connections=mp_face_mesh.FACEMESH_IRISES,
                # landmark_drawing_spec为关键点可视化样式，None为默认样式（不显示关键点）
                # landmark_drawing_spec=mp_drawing_styles.DrawingSpec(thickness=1, circle_radius=2, color=[0, 1, 128]),

                landmark_drawing_spec=None,
                connection_drawing_spec=mp_drawing_styles.get_default_face_mesh_tesselation_style())
    else:
        img = cv.putText(img, 'NO FACE DELECTED', (25 , 50 ), cv.FONT_HERSHEY_SIMPLEX, 1.25,(255, 0, 0), 1, 8)


    #记录该帧处理完毕的时间
    # end_time=time.time()
    # #计算每秒处理图像的帧数FPS
    # FPS=1/(end_time-start_time)
    # scaler=1
    # img=cv.putText(img,'FPS'+str(int(FPS)),(25*scaler,100*scaler),cv.FONT_HERSHEY_SIMPLEX,1.25*scaler,(0,0,255),1,8)
    return img


# 调用摄像头
cap=cv.VideoCapture(0)

cap.open(0)
# 无限循环，直到break被触发
while cap.isOpened():
    success,fframe=cap.read()
    frame = cv.flip(fframe,180)
    # if not success:
    #     print('ERROR')
    #     break
    frame=process_frame(frame)
    #展示处理后的三通道图像
    cv.imshow('my_window',frame)
    k = cv.waitKey(25) & 0xff
    if k == 27:  # 键盘Esc键退出
        break

cap.release()
cv.destroyAllWindows()

